package utils

import (
	red "github.com/gomodule/redigo/redis"
	redisUtils "go_batch_create_orders/package/redis"
	"time"
)

type RedisResource struct {
	pool *red.Pool
}

var redisResource RedisResource

func init() {
	//redis 初始化 https://www.cnblogs.com/feixiangmanon/p/11155120.html
	//https://blog.csdn.net/quanaianzj/article/details/84621743
	config := redisUtils.New()
	resource := RedisResource{}
	if config.Switch == false {
		//未打开开关
		resource.pool = nil
	} else {
		redisResource.pool = &red.Pool{
			MaxIdle:     config.MaxIdle,                    //最大的空闲连接数，表示即使没有redis连接时依然可以保持N个空闲的连接，而不被清除，随时处于待命状态。
			MaxActive:   config.MaxActive,                  //最大的连接数，表示同时最多有N个连接。0表示不限制。
			IdleTimeout: time.Duration(config.IdleTimeOut), //最大的空闲连接等待时间，超过此时间后，空闲连接将被关闭。如果设置成0，空闲连接将不会被关闭。应该设置一个比redis服务端超时时间更短的时间
			Dial: func() (red.Conn, error) {
				options := make([]red.DialOption, 0, 4)
				if config.DialReadTimeout > 0 {
					options = append(options, red.DialReadTimeout(time.Duration(config.DialReadTimeout)*time.Millisecond))
				}
				if config.DialWriteTimeout > 0 {
					options = append(options, red.DialWriteTimeout(time.Duration(config.DialWriteTimeout)*time.Millisecond))
				}
				if config.DialConnectTimeout > 0 {
					options = append(options, red.DialConnectTimeout(time.Duration(config.DialConnectTimeout)*time.Millisecond))
				}
				if config.Database > 0 {
					options = append(options, red.DialDatabase(config.Database))
				}
				if config.Password != "" {
					options = append(options, red.DialPassword(config.Password)) //未设置密码则直接去掉
				}
				return red.Dial(
					config.NetWork,
					config.Host+":"+config.Port,
					options...,
				)
			},
		}
	}
}

//exec, _ := utils.Exec("rpush", "helloworld", "1")
//str,_:=red.String(utils.Exec("lpop", "helloworld"))
//fmt.Println(str)  列表队列操作

func Exec(cmd string, key interface{}, args ...interface{}) (interface{}, error) {
	con := redisResource.pool.Get()
	if err := con.Err(); err != nil {
		return nil, err
	}
	defer con.Close()
	parmas := make([]interface{}, 0)
	parmas = append(parmas, key)

	if len(args) > 0 {
		for _, v := range args {
			parmas = append(parmas, v)
		}
	}
	return con.Do(cmd, parmas...)
}
